package io.github.ali.commons.variable;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.quartz.Trigger;
import org.quartz.impl.triggers.SimpleTriggerImpl;

import io.github.ali.commons.function.NAFunction;


/**
 * SimpleTrigger实现
 * 
 * @author fuli
 * @date 2018年12月4日
 * @version 1.0.0
 */
public class SimpleActionGenerator extends QuartzActionGenerator {
	private long interval;
	private TimeUnit intervalTimeUnit;
	private Date endDatetime;
	private int maxTimes = -1;
	/**
	 * 无限执行
	 * @param action
	 */
	public SimpleActionGenerator(NAFunction action) {
		super(action);
		interval = 0;
		intervalTimeUnit = TimeUnit.SECONDS;
	}
	/**
	 * 按间隔次数周期执行
	 * @param interval
	 * @param timeUnit
	 * @param action
	 */
	public SimpleActionGenerator(long interval, TimeUnit timeUnit, NAFunction action) {
		super(action);
		this.interval = interval > 0 ? interval : 0;
		this.intervalTimeUnit = timeUnit;
	}
	/**
	 * 按间隔次数周期执行最多maxTimes次
	 * @param interval
	 * @param timeUnit
	 * @param maxTimes
	 * @param action
	 */
	public SimpleActionGenerator(long interval, TimeUnit timeUnit, int maxTimes, NAFunction action) {
		super(action);
		this.interval = interval > 0 ? interval : 0;
		this.intervalTimeUnit = timeUnit;
		this.maxTimes = maxTimes <= 0 ? -1 : maxTimes;
	}

	/**
	 * 按间隔次数周期执行截至endDate
	 * @param interval
	 * @param timeUnit
	 * @param endDatetime
	 * @param action
	 */
	public SimpleActionGenerator(long interval, TimeUnit timeUnit, Date endDatetime, NAFunction action) {
		super(action);
		this.interval = interval > 0 ? interval : 0;
		this.intervalTimeUnit = timeUnit;
		this.endDatetime = endDatetime;
	}
	@Override
	protected Trigger buildTrigger() {
		SimpleTriggerImpl trigger = new SimpleTriggerImpl();
		trigger.setName(name);
		trigger.setRepeatInterval(intervalTimeUnit.toMillis(interval));
		trigger.setRepeatCount(maxTimes);
		trigger.setStartTime(new Date());
		if(endDatetime!=null) {
			trigger.setEndTime(endDatetime);
		}
		trigger.setMisfireInstruction(Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY);
		return trigger;
	}
}
